package cn.edu.hrbcu.es.invigilatemanagerment.controller;


import cn.edu.hrbcu.es.invigilatemanagerment.service.IExamInfoService;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Controller
@RequestMapping("/trainingprogram")
public class TrainingProgramController {
    @Autowired
    private IExamInfoService examInfoService;
    //文件保存路径为在D盘下的upload文件夹，可以按照自己的习惯修改
    private final static String FILE_UPLOAD_PATH = "D:\\";
    @RequestMapping("/show")
    public String showAllTrainingProgram(Model model){
        return "trainingprogram";
    }

    //    从服务器下载一个特定的文件
    @RequestMapping("DownloadFile")
    @ResponseBody
    public void downloadFile(HttpServletResponse response) throws Exception{

        examInfoService.exportExcel();
        File readFile = new File("D:/考场信息表.xlsx");
        //字节流-用于读文件  这里只是demo用的非缓冲流。实际项目可以用BufferedInputStream。 此功能是读取图片，所以用的字节流。如果是文本的话可以用字符流效率高，具体类看下面注释
        //        BufferedReader bufferedReader = new BufferedReader(new FileReader(readFile));//字符流
        FileInputStream fileInputStream = new FileInputStream(readFile);//字节流
        //设置文件下载方式
        response.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode("考场信息表.xlsx","utf-8"));
        //获取servlet响应输出字节流
        //        PrintWriter writer = response.getWriter();//字符流
        ServletOutputStream outputStream = response.getOutputStream(); //字节流

        //流数据交换，每次交换10k数据大小 （1024k = 1m）
        byte[] bytes = new byte[1024*10];
        int read;
        do {
            read = fileInputStream.read(bytes);
            outputStream.write(bytes,0,read);
        }while (-1 != read);

        String charsetName = "UTF-8";
        //outputStream.write(trainingProgram.getContent().getBytes(charsetName));

        //关闭资源
        IOUtils.closeQuietly(fileInputStream);
        IOUtils.closeQuietly(outputStream);
    }

//    将客户端上传的文件保存到服务器上
    @RequestMapping(value = "/UploadFile",method = RequestMethod.POST)
    @ResponseBody
    public String uploadFile(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()){
            return "文件上传失败";
        }
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("fileName = " + fileName);
        //生成文件名称通用方法
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random r = new Random();
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
        String newFileName = tempName.toString();
//        System.out.println("newFileName = " + newFileName);
        try {
            //保存文件
            byte[] bytes = file.getBytes();
            Path path = Paths.get(FILE_UPLOAD_PATH + newFileName);
            Files.write(path,bytes);
            examInfoService.importExcel(path);
        }catch (IOException e){
            e.printStackTrace();
            return "文件上传失败";
        }
        return "上传成功";
    }
}
